package gallery;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.View;

public class DotView extends View {

    private int count;
    private int curIndex;
    private int defaultColor;
    private int lightColor;
    private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    private int radius = 5;

    public DotView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public DotView(Context context) {
        super(context);
    }

    public void set(int count, int defaultColor, int lightColor) {
        this.count = count;
        this.defaultColor = defaultColor;
        this.lightColor = lightColor;
        this.radius = dpToPx(3);
        requestLayout();
    }

    private int dpToPx(int dp) {
        DisplayMetrics dm = getContext().getResources().getDisplayMetrics();
        return (int) (dp * dm.density + 0.5f);
    }

    public void set(int count, int defaultColor, int lightColor, int radius) {
        this.radius = dpToPx(radius);
        this.count = count;
        this.defaultColor = defaultColor;
        this.lightColor = lightColor;
        requestLayout();
    }

    public void setCurIndex(int index) {
        curIndex = index;
        postInvalidate();
    }

    public void setRadius(int radius) {
        this.radius = radius;
        requestLayout();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (count == 0) {
            return;
        }
        canvas.translate(radius, radius);
        paint.setColor(defaultColor);
        for (int i = 0; i < count; i++) {
            canvas.drawCircle(i * radius * 4, 0, radius, paint);
        }
        paint.setColor(lightColor);
        canvas.drawCircle(curIndex * radius * 4, 0, radius, paint);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        if (count == 0) {
            return;
        }
        int width = getMeasuredWidth();
        int height = getMeasuredHeight();
        int bestWidth = (count * 4 - 2) * radius;
        if (width < bestWidth) {
            radius = width / (count * 4 - 2);
            bestWidth = width;
        }
        setMeasuredDimension(bestWidth, radius * 2);
    }

}
